from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QGridLayout
from qfluentwidgets import MessageBoxBase, ComboBox, StrongBodyLabel, LineEdit, SubtitleLabel, InfoBar

from database.classes_db import ClassDB


class BaseStudentDialog(MessageBoxBase):
    def __init__(self, title,parent=None):
        super().__init__(parent)
        self.title = title
        self.setup_ui()
        self.load_classes()

    def setup_ui(self):
        self.titleLabel = SubtitleLabel(self.title,self)
        self.viewLayout.addWidget(self.titleLabel)
        self.viewLayout.setAlignment(self.titleLabel,Qt.AlignmentFlag.AlignCenter)

        grid_layout = QGridLayout()
        self.viewLayout.addLayout(grid_layout)

        self.nameInput = LineEdit(self)
        self.numberInput = LineEdit(self)
        self.genderCombo = ComboBox(self)
        self.genderCombo.addItems(['男','女'])
        self.classCombo = ComboBox(self)
        self.chineseInput = LineEdit(self)
        self.mathInput = LineEdit(self)
        self.englishInput = LineEdit(self)

        fields = [
            ("姓名：",self.nameInput),
            ("学号：",self.numberInput),
            ("性别：",self.genderCombo),
            ("班级：",self.classCombo),
            ("语文：",self.chineseInput),
            ("数学：",self.mathInput),
            ("英语：",self.englishInput),
        ]

        for row,(label_text,widget) in enumerate(fields):
            label = StrongBodyLabel(label_text,self)
            grid_layout.addWidget(label,row,0) #每行第一列
            grid_layout.addWidget(widget,row,1) #每行第二列

        grid_layout.setColumnStretch(1,1)
        grid_layout.setAlignment(Qt.AlignmentFlag.AlignLeft)

        #设置输入框的宽度
        for widget in [self.nameInput,self.numberInput,self.genderCombo,self.classCombo,self.chineseInput,self.mathInput,self.englishInput]:
            widget.setMinimumWidth(200)

        # 将焦点定位到姓名输入框
        self.nameInput.setFocus()

        #确保“确定”按钮不会自动对焦
        self.yesButton.setDefault(False)
        self.yesButton.setAutoDefault(False)

        self.yesButton.setText("确定")
        self.cancelButton.setText("取消")

    def load_classes(self):
        self.classCombo.clear()
        with ClassDB() as db:
            classes = db.fetch_classes()
        self.classCombo.addItem('请选择班级',None)
        for class_info in classes:
            self.classCombo.addItem(class_info['class_name'],userData=class_info['class_id'])

    def _validate_score(self,score):
        try:
            return 0 <= float(score) <= 100
        except ValueError:
            return False

    def _valideteInput(self):
        errors = []
        if not self.nameInput.text().split():
            errors.append("请输入学生姓名")
        if not self.numberInput.text().split():
            errors.append("请输入学生学号")
        if self.classCombo.currentData() is None:
            errors.append("请选择学生班级")
        for subject,input_field in[('语文',self.chineseInput),('数学',self.mathInput),
                                   ('英语',self.englishInput)]:
            score = input_field.text()
            if not self._validate_score(score):
                errors.append(f"{subject}分数必须是0~100")
        print(errors)
        return errors

    def accept(self):
        #对数据校验
        errors = self._valideteInput()
        if errors:
            error_message = "\n".join(errors)
            InfoBar.error(title="输入有误",content=error_message,parent=self,duration=3000)
            return
        else:
            # 校验通过
            print("数据校验通过！")
            super().accept()

class AddStudentDialog(BaseStudentDialog):
    def __init__(self, parent=None):
        super().__init__('添加学生',parent)
        self.student_id = None
        self.yesButton.setText('添加')